<?php

namespace app\agent\controller;

use app\models\{AgentArea, Agent as Agents, Region, AgentLog, Withdraw};
use think\Db;
use think\Validate;

class Agent extends Base
{



    public function agentlog()
    {
        $model = new AgentLog();
        $results = $model->order('id desc');
        $data = $this->request->get();
        if (!empty($data['id'])) {
            $agentid = $data['id'];
        } else {
            $agentid = $this->request->agent['id'];
        }
        $results = $results->where(['user_id' => $agentid]);
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        return view(null, [
            'list' => $results
        ]);
    }

    public function index()
    {
        $model = new Agents();
        $data = $this->request->get();
        $results = $model->order('id desc');
        $where = [];
        $where1 = [];
        if (!empty($data['title'])) {
            $where[] = ['accounts|nickname', 'like', '%' . $data['title'] . '%'];
            $where1[] = ['accounts|nickname', 'like', '%' . $data['title'] . '%'];
        }
        $where[] = ['id', 'IN', $this->request->agentlist];
        $where1[] = ['topid', '=', $this->request->agent['id']];
        $results = $results->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        });
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            $result['allincome'] = (new AgentLog())->where(['user_id' => $result['id'], 'type' => [1, 2]])->sum('money') ?? 0;
            $result['allincome'] = $result['allincome'] + $result['allmoney'];
            $result['money'] = $result['money'] + $result['tmoney'];
        }
        return view(null, [
            'list' => $results
        ]);
    }

    public function agent_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'nickname' => 'require',
                'accounts' => 'require',
            ], [
                'nickname.require' => '昵称不能为空',
                'accounts.require' => '账号不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Agents();
            //查找店铺名称、账号是否已经被使用
            $haveshop = $model->where('accounts', $data['accounts'])->find();
            if (!empty($data['id'])) {
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                if (!in_array($data['id'], $this->request->agentlist)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '该代理不属于您管辖区域，请查看区域范围或者添加代理区域']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $data['topid'] = $this->request->agent['id'];
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Agents();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }

    public function agentarea()
    {
        $list = (new AgentArea())->order('id desc');
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('title', 'like', '%' . $data['title'] . '%');
        }
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        if (!empty($data['agentid'])) {
            $list = $list->where(['agentid' => $data['agentid']]);
        }
        if ($this->request->agent['id'] != $data['agentid']) {
            $list = $list->where(['agentid' => $this->request->agentlist]);
        }
        if (!empty($data['province'])) {
            $city_top = (new Region())->where(['level' => 1, 'area_code' => $data['province']])->value('id') ?? 0;
            $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            $list = $list->where(['province' => $data['province']]);
        }
        if (!empty($data['city'])) {
            $area_top = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->value('id') ?? 0;
            $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
            $list = $list->where(['city' => $data['city']]);
        }
        if (!empty($data['area'])) {
            $street_top = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->value('id') ?? 0;
            $street = (new Region())->where(['level' => 4, 'parent_id' => $street_top])->select();
            $list = $list->where(['area' => $data['area']]);
        }
        if (!empty($data['street'])) {
            $list = $list->where(['street' => $data['street']]);
        }
        $list = $list->paginate(10)->each(function ($row) {
            $row['province_list'] = [];
            $row['city_list'] = [];
            $row['area_list'] = [];
            $row['street_list'] = [];
            $row['agent_name'] = (new Agents())->where(['id' => $row['agentid']])->value('nickname') ?? '';
            $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '';
            $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '';
            $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '';
            $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '';
            return $row;
        });
        $agent = (new Agents())->where(['id' => $this->request->agentlist])->field('id,nickname,accounts')->select();
        return view(null, [
            'list' => $list,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'street' => $street,
            'agent' => $agent,
            'agentid' => $this->request->agent['id']
        ]);
    }

    public function agentarea_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'agentid' => 'require',
                'type' => 'require|in:2,3,4'
            ], [
                'agentid.require' => '服务商家不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确'
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            if ($this->request->agent['id'] == $data['agentid']) {
                return json(['status' => 1, 'msg' => '请联系总管理员或上级代理人']);
            }
            switch ($data['type']) {
                case '3':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    //查看是否有区域权限
                    $agentauth = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $data['city']])->find();
                    if (empty($agentauth)) {
                        return json(['status' => 1, 'msg' => '无该区域添加权限']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['status' => 1, 'msg' => '该代理已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加高级别需要删除低级别权限
                    $havearea = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 4, 'area' => $data['area']])->find();
                    if (!empty($havearea)) {
                        return json(['status' => 1, 'msg' => '添加或更改更高级别区域管理前请先确认并删除低级别区域管理权限']);
                    }
                    $data['street'] = 0;
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['status' => 1, 'msg' => '请选择街道']);
                    }
                    //查看是否有区域权限
                    $agentauth = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $data['city']])->find();
                    $agentauth1 = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 3, 'area' => $data['area']])->find();
                    if (empty($agentauth) && empty($agentauth1)) {
                        return json(['status' => 1, 'msg' => '无该街道添加权限']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['status' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat2 = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 3, 'area' => $data['area']])->find();
                    if (!empty($haveareat2)) {
                        return json(['status' => 1, 'msg' => '您已拥有高级别的区域管理，无需再添加低级别区域管理']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '代理区域类型错误']);
                    break;
            }
            //查询负责区域是否已存在
            $businessarea = (new AgentArea())->where([
                'type' => $data['type'],
                'province' => $data['province'],
                'city' => $data['city'],
                'area' => $data['area'],
                'street' => $data['street']
            ])->find();
            if (!empty($businessarea)) {
                return json(['status' => 1, 'msg' => '管理区域已添加或已被分配']);
            }
            $res = (new AgentArea())->allowfield(true)->save($data);
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new AgentArea())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            $agent = (new Agents())->whereor(['id' => $this->request->agentlist])->whereor(['topid' => $this->request->agent['id']])->field('id,nickname,accounts')->where('status', 1)->select();
            if (!empty($row)) {
                $parent = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->find();
                $city = (new Region())->where(['level' => 2, 'parent_id' => $parent['id']])->select();
                $carent = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->find();
                $area = (new Region())->where(['level' => 3, 'parent_id' => $carent['id']])->select();
                $aarent = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->find();
                $street = (new Region())->where(['level' => 4, 'parent_id' => $aarent['id']])->select();
            } else {
                $agentid = $this->request->get('agentid/d', 0);
                if (!empty($agentid)) {
                    $row['agentid'] = $agentid;
                }
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'agent' => $agent
            ]);
        }
    }


    public function agentarea_del()
    {
        $id = trim(input('id'), ',');
        $model = new AgentArea();
        $areas = $model->where(['id' => $id])->find();
        if (empty($areas)) {
            return json(['status' => 1, 'msg' => '信息不存在']);
        }
        if ($this->request->agent['id'] == $areas['agentid']) {
            return json(['status' => 1, 'msg' => '请联系总管理员或上级代理人操作']);
        }
        if ($areas['type'] == 3) {
            $agentauth = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $areas['city']])->find();
        }
        if ($areas['type'] == 4) {
            $agentauth = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $areas['city']])->find();
            if (empty($agentauth)) {
                $agentauth = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 3, 'area' => $areas['area']])->find();
            }
        }
        if (empty($agentauth)) {
            return json(['status' => 1, 'msg' => '无操作权限']);
        }
        $res = $model->where(['id' => $id])->delete();

        if ($res) {
            return json(['code' => 0, 'status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'status' => 0, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function widtraw()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'money' => 'require|gt:10',
                'name' => 'require',
                'cards' => 'require',
                'bank' => 'require',
                'password' => 'require'
            ], [
                'money.require' => '提现金额不能为空',
                'money.gt' => '提现金额必须大于10元',
                'name.require' => '提现用户不能为空',
                'cards.require' => '提现卡号不能为空',
                'bank.require' => '提现行不能为空',
                'password.require' => '商户密码不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            //判断是否超出商家运营范围
            if ($this->request->agent['money'] < $data['money']) {
                return json(['status' => 1, 'msg' => '可提现金额不足']);
            }
            if ($this->request->agent['password'] != md5(md5($data['password']))) {
                return json(['status' => 1, 'msg' => '密码不正确']);
            }
            Db::startTrans();
            try {
                (new Agents())->MoneyEdit($this->request->agent['id'], 3, -$data['money'], '代理提现', 0);
                (new Withdraw())->allowfield(true)->save([
                    'type' => 2,
                    'user_id' => $this->request->agent['id'],
                    'money' => $data['money'],
                    'name' => $data['name'],
                    'cards' => $data['cards'],
                    'bank' => $data['bank'],
                    'status' => 1
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'code' => 1, 'msg' => '操作失败']);
            }
            return json(['status' => 0, 'code' => 0, 'msg' => '操作成功']);
        } else {
            $agent = $this->request->agent;
            $agent['money'] = $agent['money'] + $agent['tmoney'];
            return view('', [
                'business' => $agent
            ]);
        }
    }


    public function widtrawlog()
    {
        $results = (new Withdraw())->order('id desc')->where(['type' => 2, 'user_id' => $this->request->agent['id']]);
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            if ($result['status'] == 1) {
                $result['status_text'] = '待审核';
            }
            if ($result['status'] == 2) {
                $result['status_text'] = '审核通过';
            }
            if ($result['status'] == 3) {
                $result['status_text'] = '平台或代理取消';
            }
        }
        return view(null, [
            'list' => $results
        ]);
    }

    public function widtrawstr()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require'
        ], [
            'id.require' => 'ID不能为空'
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'msg' =>  $validate->getError()]);
        }
        $withdraw = (new Withdraw())->order('id desc')->where(['type' => 2, 'id' => $data['id'], 'user_id' => $this->request->agent['id'], 'status' => 1])->find();
        if (empty($withdraw)) {
            return json(['status' => 1, 'msg' =>  '记录不可操作']);
        }
        Db::startTrans();
        try {
            (new Agents())->MoneyEdit($this->request->agent['id'], 3, $withdraw['money'], '代理提现自主取消', 0);
            (new Withdraw())->where(['id' => $data['id'], 'status' => 1, 'type' => 2])->update(['status' => 3]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'code' => 1, 'msg' => '操作失败']);
        }
        return json(['status' => 0, 'code' => 0, 'msg' => '操作成功']);
    }
}
